#!/usr/bin/env bash

SCRIPT_DIR="$(dirname "$(realpath "$0")")"
# shellcheck source=src/lib/rsdk/utils.sh
source "$SCRIPT_DIR/../../lib/rsdk/utils.sh"

if (($# < 2)); then
	error "$EXIT_TOO_FEW_ARGUMENTS"
fi

IMAGE="$1"
BLOCKDEV="$2"

if [[ ! -f $IMAGE ]]; then
	error "$EXIT_FILE_NOT_EXIST" "$IMAGE"
elif [[ ! -b $BLOCKDEV ]]; then
	echo "$EXIT_NOT_BLOCK_DEVICE" "$BLOCKDEV"
fi

# Prepopulate sudo token, so echo message won't be mixed with password prompt
env sudo -v
(
	EXT="${IMAGE##*.}"
	case "$(file "$IMAGE")" in
	*"XZ compressed"*)
		EXT="xz"
		;;
	*"gzip compressed data"*)
		EXT="gz"
		;;
	*"Zip archive"*)
		EXT="zip"
		;;
	*"7-zip archive data"*)
		EXT="7z"
		;;
	*"Zstandard compressed data"*)
		EXT="zstd"
		;;
	*"RAR archive data"*)
		EXT="rar"
		;;
	esac

	case "$EXT" in
	"xz")
		echo "Writing xz image..." >&2
		xzcat "$IMAGE"
		;;
	"gz")
		echo "Writing gz image..." >&2
		zcat "$IMAGE"
		;;
	"zip")
		echo "Writing zip image..." >&2
		unzip -p "$IMAGE"
		;;
	"7z")
		echo "Writing 7-zip image..." >&2
		7z e -so "$IMAGE"
		;;
	"zstd")
		echo "Writing Zstd image..." >&2
		zstdcat "$IMAGE"
		;;
	"rar")
		echo "Writing RAR image..." >&2
		7z e -so "$IMAGE"
		;;
	*)
		echo "Writing raw image..." >&2
		cat "$IMAGE"
		;;
	esac
) | sudo dd "of=$BLOCKDEV" bs=16M status=progress
echo "Syncing block device..."
sudo sync "$BLOCKDEV"
echo "$IMAGE has been written to $BLOCKDEV."
